//
//  SZLNormalShopsViewController.m
//  Shengzhuli
//
//  Created by 卡忙科技 on 16/7/25.
//  Copyright © 2016年 kamangkeji. All rights reserved.
//

#import "SZLNormalShopsViewController.h"
#import "NormalShopTableViewCell.h"
#import "NormalShopCollectionViewCell.h"
#import <MJRefresh.h>
#import "SingleNetService.h"
#import "ShopConditionToolBar.h"
#import "MBProgressHUD+MJ.h"

@interface SZLNormalShopsViewController()<UITextFieldDelegate,UITableViewDataSource,UITableViewDelegate,UICollectionViewDataSource,UICollectionViewDelegate,ShopConditionToolBarDelegate>
{
    BOOL isAnimate;//记录是否播放过开场动画
}
//----------------
@property (nonatomic,weak) UITextField *search;
@property (nonatomic,assign) NSInteger curPage;
//----------------
@property (nonatomic,assign) ConditionType conditionType;
@property (nonatomic,assign) AdType adType;
//----------------
@property (nonatomic,weak) ShopConditionToolBar *conditionToolBar;
@property (nonatomic,strong) NSMutableArray *sources;
@property (nonatomic,strong) UITableView *sourceTab;
@property (nonatomic,strong) UICollectionView *sourceCollection;

@end
@implementation SZLNormalShopsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.automaticallyAdjustsScrollViewInsets = NO;
    isAnimate = NO;
    [self setNav];
    [self setView];
    //[self showRequestAgainView:@selector(getGoodsList)];
    [self getGoodsList];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}
- (void)switchCollection:(UIButton *)btn
{
    btn.selected = !btn.selected;
    if (self.sources.count == 0) return;
    if (btn.selected) {
        [self.view addSubview:self.sourceCollection];
        self.sourceCollection.hidden = NO;
        self.sourceTab.hidden = YES;
    }else{
        self.sourceTab.hidden = NO;
        self.sourceCollection.hidden = YES;
    }
}
//开场动画
- (void)doanimations
{
    isAnimate = YES;
    NSArray *cells = self.sourceTab.visibleCells;
    for (UITableViewCell *cell in cells) {
        cell.transform = CGAffineTransformMakeTranslation(ScreenW, 0);
    }
    NSInteger index = 0;
    for (UITableViewCell *cell in cells) {
        [UIView animateWithDuration:1.2 delay:0.1 * index usingSpringWithDamping:0.8 initialSpringVelocity:8 options:UIViewAnimationOptionCurveEaseInOut animations:^{
            cell.transform = CGAffineTransformIdentity;
        } completion:nil];
        index++;
    }
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    self.curPage = 1;
    [self.search resignFirstResponder];
    [self getGoodsList];
    return YES;
}
#pragma mark --------------------shopConditionDelegate--------------------------------------
- (void)shopConditionToolBarClick:(ConditionType)conditionType aDType:(AdType)adType
{
    self.conditionType = conditionType;
    self.adType = adType;
    self.curPage = 1;//重置当前页数
    [self getGoodsList];
}
#pragma mark ------------------------请求相关--------------------------------------
- (void)getGoodsList
{
    NSMutableDictionary *parame = [NSMutableDictionary dictionary];
    parame[@"name"] = self.search.text;
    parame[@"pageNo"] = @(self.curPage);
    //parame[@"cityId"] = @(self.model.ID);
    parame[@"orderByType"] = self.conditionType>0?@(self.conditionType):@"";
    parame[@"orderBySort"] = self.adType>0?@(self.adType):@"";
    [self showWaiter];
    [SingleNetService normalShopSearchWithParame:parame response:^(BOOL success, NSString *msg, NSArray *gooods) {
        [self hideWaiter];
        [self hideRequestAgainView];
        [self.sourceTab.mj_header endRefreshing];
        [self.sourceTab.mj_footer endRefreshing];
        [self.sourceCollection.mj_header endRefreshing];
        [self.sourceCollection.mj_footer endRefreshing];
        
        self.sourceTab.mj_footer.hidden = (gooods.count < 20);
        self.sourceCollection.mj_footer.hidden = (gooods.count < 20);
        if (success) {
            if (self.curPage == 1) {
                [self.sources removeAllObjects];
                if (gooods.count == 0) {
                    [self showNoDataView:CGRectMake(0, 0, ScreenW, ScreenH-64) title:@"抱歉,没有符合条件的商品"];
                    return ;
                }else{
                    [self hideNoDataView];
                }
            }else{//上拉加载更多逻辑
                self.curPage = (gooods.count>0)?self.curPage:(self.curPage--);
            }
            [self.sources addObjectsFromArray:gooods];
            [self.sourceTab reloadData];
            if (!isAnimate) {
                [self doanimations];//开场动画
            }
            [self.sourceCollection reloadData];
        }else{
            if ([msg isEqualToString:NoNetworkStatus]) {
                if (self.sources.count == 0) {
                    [self showRequestAgainView:@selector(getGoodsList)];
                }
            }
            [MBProgressHUD showError:msg toView:self.view];
        }
    }];
}
#pragma mark ----------------view相关--------------------------------------
- (void)setNav
{
    self.curPage = 1;
    UITextField *search = [[UITextField alloc]initWithFrame:CGRectMake(45, 27, ScreenW-60, 30)];
    search.borderStyle = UITextBorderStyleNone;
    search.layer.cornerRadius = 15.0;
    search.clipsToBounds = YES;
    search.placeholder = @"搜索普通商品";
    search.backgroundColor = [UIColor whiteColor];
    UIImageView *leftImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 20, 25)];
    leftImage.image = [UIImage imageNamed:@"searchbar_textfield"];
    leftImage.contentMode = UIViewContentModeRight;
    search.leftView = leftImage;
    search.leftViewMode = UITextFieldViewModeAlways;
    search.font = [UIFont systemFontOfSize:15];
    search.returnKeyType = UIReturnKeySearch;
    search.delegate = self;
    self.search = search;
    self.navigationItem.titleView = search;
    
    UIButton *switchBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 22, 22)];
    [switchBtn setImage:[UIImage imageNamed:@"switch_two"] forState:UIControlStateNormal];
    [switchBtn setImage:[UIImage imageNamed:@"switch_one"] forState:UIControlStateSelected];
    [switchBtn addTarget:self action:@selector(switchCollection:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:switchBtn];
}
- (void)setView
{
    ShopConditionToolBar *conditionToolBar = [[ShopConditionToolBar alloc]initWithFrame:CGRectMake(0, 0, ScreenW, 40)];
    self.conditionToolBar = conditionToolBar;
    conditionToolBar.delegate = self;
    [self.view addSubview:conditionToolBar];
    [self.view addSubview:self.sourceTab];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.sources.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NormalShopTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([NormalShopTableViewCell class])];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.model = self.sources[indexPath.row];
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(NormalShopTableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)viewDidLayoutSubviews
{
    if ([self.sourceTab respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.sourceTab setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.sourceTab respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.sourceTab setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (UITableView *)sourceTab
{
    if (!_sourceTab) {
        _sourceTab = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.conditionToolBar.frame), ScreenW, ScreenH-64-self.conditionToolBar.height)];
        _sourceTab.dataSource = self;
        _sourceTab.delegate = self;
        [_sourceTab registerNib:[UINib nibWithNibName:NSStringFromClass([NormalShopTableViewCell class]) bundle:[NSBundle mainBundle]] forCellReuseIdentifier:NSStringFromClass([NormalShopTableViewCell class])];
        _sourceTab.rowHeight = 120;
        _sourceTab.tableFooterView = [[UIView alloc]init];
        _sourceTab.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.curPage = 1;
            [self getGoodsList];
        }];
        _sourceTab.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.curPage++;
            [self getGoodsList];
        }];
    }
    return _sourceTab;
}
- (UICollectionView *)sourceCollection
{
    if (!_sourceCollection) {
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 10;
        layout.minimumInteritemSpacing = 10;
        CGFloat itemW = (ScreenW-10)/2.0;
        layout.itemSize = CGSizeMake(itemW, itemW+70);
        _sourceCollection = [[UICollectionView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.conditionToolBar.frame), ScreenW, ScreenH-64-self.conditionToolBar.height) collectionViewLayout:layout];
        _sourceCollection.backgroundColor = RGBColorOne(235);
        _sourceCollection.delegate = self;
        _sourceCollection.dataSource = self;
        [_sourceCollection registerNib:[UINib nibWithNibName:NSStringFromClass([NormalShopCollectionViewCell class]) bundle:nil] forCellWithReuseIdentifier:NSStringFromClass([NormalShopCollectionViewCell class])];
        _sourceCollection.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            self.curPage = 1;
            [self getGoodsList];
        }];
        _sourceCollection.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
            self.curPage++;
            [self getGoodsList];
        }];
        _sourceCollection.hidden = YES;
    }
    return _sourceCollection;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.sources.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    NormalShopCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:NSStringFromClass([NormalShopCollectionViewCell class]) forIndexPath:indexPath];
    cell.model = self.sources[indexPath.row];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
}

#pragma mark ------------------------------------------------------
- (NSMutableArray *)sources
{
    if (!_sources) {
        _sources = [NSMutableArray array];
    }
    return _sources;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    [self.search resignFirstResponder];
}


@end
